// 通用JavaScript功能

// 当文档加载完成后执行
document.addEventListener('DOMContentLoaded', function() {
    // 初始化工具提示
    initTooltips();
    
    // 初始化下拉菜单
    initDropdowns();
    
    // 初始化折叠面板
    initCollapsibles();
});

// 初始化工具提示
function initTooltips() {
    const tooltips = document.querySelectorAll('.tooltip');
    
    tooltips.forEach(tooltip => {
        const tooltipText = tooltip.querySelector('.tooltip-text');
        if (!tooltipText) return;
        
        tooltip.addEventListener('mouseenter', () => {
            tooltipText.style.visibility = 'visible';
            tooltipText.style.opacity = '1';
        });
        
        tooltip.addEventListener('mouseleave', () => {
            tooltipText.style.visibility = 'hidden';
            tooltipText.style.opacity = '0';
        });
    });
}

// 初始化下拉菜单
function initDropdowns() {
    const dropdowns = document.querySelectorAll('.dropdown');
    
    dropdowns.forEach(dropdown => {
        const trigger = dropdown.querySelector('.dropdown-trigger');
        const menu = dropdown.querySelector('.dropdown-menu');
        
        if (!trigger || !menu) return;
        
        trigger.addEventListener('click', (e) => {
            e.preventDefault();
            e.stopPropagation();
            
            const isActive = menu.classList.contains('active');
            
            // 关闭所有其他下拉菜单
            document.querySelectorAll('.dropdown-menu.active').forEach(activeMenu => {
                if (activeMenu !== menu) {
                    activeMenu.classList.remove('active');
                }
            });
            
            // 切换当前下拉菜单
            menu.classList.toggle('active', !isActive);
        });
    });
    
    // 点击页面其他地方关闭下拉菜单
    document.addEventListener('click', () => {
        document.querySelectorAll('.dropdown-menu.active').forEach(menu => {
            menu.classList.remove('active');
        });
    });
}

// 初始化折叠面板
function initCollapsibles() {
    const collapsibles = document.querySelectorAll('.collapsible');
    
    collapsibles.forEach(collapsible => {
        const trigger = collapsible.querySelector('.collapsible-trigger');
        const content = collapsible.querySelector('.collapsible-content');
        
        if (!trigger || !content) return;
        
        trigger.addEventListener('click', () => {
            const isOpen = collapsible.classList.contains('open');
            
            if (isOpen) {
                collapsible.classList.remove('open');
                content.style.maxHeight = '0';
            } else {
                collapsible.classList.add('open');
                content.style.maxHeight = content.scrollHeight + 'px';
            }
        });
    });
}

// 格式化数字
function formatNumber(number, decimals = 0, decimalSeparator = '.', thousandsSeparator = ',') {
    const fixedNumber = parseFloat(number).toFixed(decimals);
    const parts = fixedNumber.split('.');
    
    parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, thousandsSeparator);
    
    return parts.join(decimalSeparator);
}

// 防抖函数
function debounce(func, wait = 300) {
    let timeout;
    
    return function executedFunction(...args) {
        const later = () => {
            clearTimeout(timeout);
            func(...args);
        };
        
        clearTimeout(timeout);
        timeout = setTimeout(later, wait);
    };
}

// 节流函数
function throttle(func, limit = 300) {
    let inThrottle;
    
    return function executedFunction(...args) {
        if (!inThrottle) {
            func(...args);
            inThrottle = true;
            setTimeout(() => inThrottle = false, limit);
        }
    };
}

// 获取 URL 参数
function getUrlParameter(name) {
    name = name.replace(/[\[]/, '\\[').replace(/[\]]/, '\\]');
    const regex = new RegExp('[\\?&]' + name + '=([^&#]*)');
    const results = regex.exec(location.search);
    return results === null ? '' : decodeURIComponent(results[1].replace(/\+/g, ' '));
}

// 显示通知
function showNotification(message, type = 'info', duration = 3000) {
    // 创建通知元素
    const notification = document.createElement('div');
    notification.className = `notification notification-${type}`;
    
    // 设置图标
    let icon = 'info-circle';
    if (type === 'success') icon = 'check-circle';
    if (type === 'warning') icon = 'exclamation-triangle';
    if (type === 'error') icon = 'times-circle';
    
    notification.innerHTML = `
        <i class="fas fa-${icon} notification-icon"></i>
        <div class="notification-message">${message}</div>
    `;
    
    // 添加到文档
    document.body.appendChild(notification);
    
    // 淡入效果
    setTimeout(() => {
        notification.classList.add('show');
    }, 10);
    
    // 淡出并移除
    setTimeout(() => {
        notification.classList.remove('show');
        notification.addEventListener('transitionend', () => {
            notification.remove();
        });
    }, duration);
}

// 动态加载 CSS
function loadCSS(url) {
    return new Promise((resolve, reject) => {
        const link = document.createElement('link');
        link.rel = 'stylesheet';
        link.href = url;
        
        link.onload = () => resolve(link);
        link.onerror = () => reject(new Error(`无法加载样式: ${url}`));
        
        document.head.appendChild(link);
    });
}

// 动态加载 JavaScript
function loadScript(url) {
    return new Promise((resolve, reject) => {
        const script = document.createElement('script');
        script.src = url;
        
        script.onload = () => resolve(script);
        script.onerror = () => reject(new Error(`无法加载脚本: ${url}`));
        
        document.body.appendChild(script);
    });
}

// 本地存储工具
const storage = {
    set(key, value) {
        try {
            localStorage.setItem(key, JSON.stringify(value));
        } catch (e) {
            console.error('存储到 localStorage 失败:', e);
        }
    },
    get(key, defaultValue = null) {
        try {
            const value = localStorage.getItem(key);
            return value ? JSON.parse(value) : defaultValue;
        } catch (e) {
            console.error('从 localStorage 获取失败:', e);
            return defaultValue;
        }
    },
    remove(key) {
        try {
            localStorage.removeItem(key);
        } catch (e) {
            console.error('从 localStorage 删除失败:', e);
        }
    },
    clear() {
        try {
            localStorage.clear();
        } catch (e) {
            console.error('清除 localStorage 失败:', e);
        }
    }
}; 